﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace 识别文件真实类型
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                lblFilePath.Text = ofd.FileName;
            }
        }

        /// <summary>
        /// 选择文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                lblFolderPath.Text = fbd.SelectedPath;
            }
        }

        /// <summary>
        /// 检查操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCheck_Click(object sender, EventArgs e)
        {
            if (lblFilePath.Text.Trim() == "")
            {
                MessageBox.Show("文件类型检查只针对单文件，请选择文件！");
                return;
            }
            string filetypevalue = GetFileTypeValue(lblFilePath.Text);

            MessageBox.Show("文件类型值为：" + filetypevalue);

            string filetype = GetFileTypeName(int.Parse(filetypevalue));

            MessageBox.Show("文件类型名为：" + filetype);
        }

        private delegate bool ParameterizedThreadStart(string filepath);

        /// <summary>
        /// 处理操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSet_Click(object sender, EventArgs e)
        {
            if (radioFile.Checked || radioFolder.Checked)
            {
                if (radioFolder.Checked)
                {
                    if(lblFolderPath.Text.Trim()=="")
                    {
                        MessageBox.Show("请选择文件夹！");
                    }
                    else
                    {
                        DirectoryInfo folder = new DirectoryInfo(lblFolderPath.Text.Trim());
                        FileInfo [] filelist=folder.GetFiles();

                        int num = 0;
                        foreach(FileInfo fi in filelist)
                        {
                            string FilePath = fi.FullName;

                            string ExtStr = Path.GetExtension(FilePath);
                            string GetExtStr = "." + GetFileTypeName(int.Parse(GetFileTypeValue(FilePath)));

                            if (ExtStr.ToLower() != GetExtStr.ToLower())
                            {
                                string NewPath = Path.ChangeExtension(FilePath, GetExtStr);
                                File.Move(FilePath, NewPath);

                                File.Delete(FilePath);
                            }
                            else
                            {
                                num++;
                            }
                        }

                        MessageBox.Show("已处理完成，其中"+num+"个文件正常，修改文件"+(filelist.Length-num).ToString()+"个");
                    }
                }
                else
                {
                    string ExtStr = Path.GetExtension(lblFilePath.Text.Trim());

                    string GetExtStr = "."+GetFileTypeName(int.Parse(GetFileTypeValue(lblFilePath.Text.Trim())));

                    if (ExtStr.ToLower() == GetExtStr.ToLower())
                    {
                        MessageBox.Show("该文件后缀名正确，无需处理！");
                    }
                    else
                    {
                        string NewPath=Path.ChangeExtension(lblFilePath.Text.Trim(), GetExtStr);
                        File.Move(lblFilePath.Text.Trim(), NewPath);

                        File.Delete(lblFilePath.Text.Trim());
                        lblFilePath.Text = NewPath;
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择操作类型！");
            }
        }

        /// <summary>
        /// 根据文件获取文件头值
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        string GetFileTypeValue(string path)
        {
            System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
            string bx = " ";
            byte buffer;
            try
            {
                buffer = r.ReadByte();
                bx = buffer.ToString();
                buffer = r.ReadByte();
                bx += buffer.ToString();
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
            r.Close();
            fs.Close();

            if(bx.Trim()=="")
            {
                bx = "0";
            }

            //文件名，包括格式
            Console.WriteLine(System.IO.Path.GetFileName(path));
            //文件名， 不包括格式
            Console.WriteLine(System.IO.Path.GetFileNameWithoutExtension(path));
            //文件格式
            Console.WriteLine(System.IO.Path.GetExtension(path));

            //真实的文件类型
            return bx;
        }
        
        /// <summary>
        /// 根据文件头值获取文件类型名
        /// </summary>
        /// <param name="typevalue"></param>
        /// <returns></returns>
        string GetFileTypeName(int typevalue)
        {
            string filetype = System.Enum.GetName(typeof(FileExtension), typevalue);

            return filetype;
        }

        /// <summary>
        /// 文件头值对应类型名
        /// </summary>
        enum FileExtension
        {
            JPG = 255216,
            GIF = 7173,
            BMP = 6677,
            PNG = 13780,
            //COM = 7790,
            EXE = 7790,
            //DLL = 7790,
            RAR = 8297,
            ZIP = 8075,
            XML = 6063,
            HTML = 6033,
            ASPX = 239187,
            CS = 117115,
            JS = 119105,
            TXT = 210187,
            SQL = 255254,
            BAT = 64101,
            BTSEED = 10056,
            RDP = 255254,
            PSD = 5666,
            PDF = 3780,
            CHM = 7384,
            LOG = 70105,
            REG = 8269,
            HLP = 6395,
            DOC = 208207,
            XLS = 208207,
            DOCX = 208207,
            XLSX = 208207,
            WMV = 2669,
        }

    }
}
